package com.frxuexi.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.entity.ApiResponse
import com.frxuexi.lib_base.entity.BaseEntity
import com.frxuexi.lib_base.entity.LocalEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.io.File

abstract class BaseViewModel<UiIntent:IUiIntent>:ViewModel() {
    //存放管理意图的管道
    val channel= Channel<UiIntent>(Channel.UNLIMITED)

    //用于更新UI的状态封装
    private var _state=MutableStateFlow<UiState>(UiState.onLoading)
    val state:StateFlow<UiState>
        get() = _state

    init {
        viewModelScope.launch {
//            接收意图
            channel.receiveAsFlow().collect{
                handleIntent(it)
            }
        }
    }

    /**
     * 处理意图
     */
    abstract fun handleIntent(it:UiIntent)

    /**
     * 发送意图
     */
    fun sendIntent(it:UiIntent){
        viewModelScope.launch {
            channel.send(it)
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest(request:Flow<ApiResponse<Any>>,type: HttpType=HttpType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)//子线程
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.statusCode==200){
                        _state.value=UiState.onSuccess(it.data?:it.datas,type)
                    }else{
                        _state.value=UiState.onError(it.msg!!)
                    }
                }
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest2(request:Flow<BaseEntity<Any>>,type: HttpType=HttpType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)//子线程
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.code==0){
                        _state.value=UiState.onSuccess(it.data,type)
                    }else{
                        _state.value=UiState.onError(it.msg!!)
                    }
                }
        }
    }

    /**
     * room请求
     */
    fun roomRequest(request:Flow<Any>,type: HttpType=HttpType.DEFAULT){
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)//子线程
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it!=null){
                        _state.value=UiState.onSuccess(it,type)
                    }else{
                        _state.value=UiState.onError("操作错误")
                    }
                }
        }
    }

    fun downloadApk(url:String,path:File){
        viewModelScope.launch {
            DownLoadUtil.download(url,path).flowOn(Dispatchers.IO)
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    _state.value=it
                }
        }
    }

    fun scan(file: File){
        viewModelScope.launch {
            try {
                val files = file.listFiles()
                val list = mutableListOf<LocalEntity>()
                for (f in files){
                    list.add(LocalEntity(f.name,f.path))
                }
                _state.value=UiState.onSuccess(list,HttpType.SCAN)
            }catch (e:Exception){
                _state.value=UiState.onError(e.message.toString())
            }


        }
    }
}